var event = require('../../core/event');
var config = require('../../core/config');
var $ = window.$;
var notify = require('../notify/ui');
var gui = require("gui");
var open = require("open");
var record = require('../../core/record');
var enums = require('../../core/enum');
var input = require('../../core/input');
var util = require('../../util/index');
var path = require('path');

var _init = false;

/**
 * 虽然名字叫menu, 实际是承担了所有UI的处理
 */

var ret = {
    init: function () {
        if (_init) {
            return;
        }
        this.parent = $('#menu');

        if(process.platform === 'darwin'){
            var win = gui.Window.get();
            var nativeMenuBar = new gui.Menu({ type: "menubar" });
            nativeMenuBar.createMacBuiltin("NoteArt");
            win.menu = nativeMenuBar;
        }
        $('#menus').on('click', '.sub-menu-item[data-action]', function (e) {
            e.preventDefault();
            e.stopPropagation();
            var act = e.currentTarget.dataset.action;
            if(!act){
                return;
            }
            if($(this).hasClass("disable")){
                return;
            }
            //临时拦截一部分action, 以后有UI了再移出去
            if(act == event.events.app.exit){
                gui.Window.get().close();
                return;
            }else if(act == event.events.app.showConsole){
                gui.Window.get().showDevTools();
                return;
            }else if(act == event.events.global.undo){
				record.undo();
				return;
			}else if(act == event.events.global.redo){
				record.redo();
				return;
			}else if(act == event.events.tutorial.show){
                event.trigger(event.events.tutorial.show,"mainwindow");
                return;
            }else if(act == event.events.urlopen.website){
                open("http://m.mugzone.net/");
                return;
            }else if(act == event.events.urlopen.song){
				var note = require('../note/manager');
				var chart = note.getNote('main');
				if(chart && chart.meta.song.id){
					open("http://m.mugzone.net/song/"+chart.meta.song.id);
				}else{
					notify.addNotify({
						msg: config.i18n("err25")
					});
				}
			}else if(act == event.events.urlopen.chart){
				var note = require('../note/manager');
				var chart = note.getNote('main');
				if(chart && chart.meta.id){
					open("http://m.mugzone.net/chart/"+chart.meta.id);
				}else{
					notify.addNotify({
						msg: config.i18n("err25")
					});
				}
			}
            event.trigger(e.currentTarget.dataset.action);
        });
        this.parent.find('.tool').on('click', 'span', function (e) {
            var target = $(this);
            if(target.attr('id') == 'min'){
                gui.Window.get().minimize();
            }else{
                gui.Window.get().close();
            }
        });
        //不是默认语言时, menu上的文字要替换
        if(!config.isDefaultLang()){
            this.doLangReplace();
        }
		this.checkMenuItems();

		event.bind(event.events.key.up,'menu', this);
		event.bind(event.events.note.load, 'menu', this);
		event.bind(event.events.note.unload, 'menu', this);
		event.bind(event.events.global.drop, 'menu', this);
        _init = true;
    },

	onEvent: function (e, param) {
        var self = this;
		if(e == event.events.key.up){
            if(this.isCtrlPressed){
                setTimeout(function(){
                    self.isCtrlPressed = false;
                }, 1500);
            }
			switch(param.key){
				case enums.KEY.F5:
					event.trigger(event.events.test.start);
					return true;
			}
			switch (param.key){
				case enums.KEY.C:
					event.trigger(event.events.global.copy);
					return true;
				case enums.KEY.E:
					event.trigger(event.events.file.exports);
					return true;
				case enums.KEY.O:
					event.trigger(event.events.file.load);
					return true;
				case enums.KEY.S:
					event.trigger(event.events.file.save);
					return true;
				case enums.KEY.U:
					if(input.isCtrl() && input.isAlt()){
						event.trigger(event.events.dialog.upload2);
					}else{
						event.trigger(event.events.file.upload);
					}
					return true;
				case enums.KEY.V:
					event.trigger(event.events.global.paste);
					return true;
				case enums.KEY.H:
					event.trigger(event.events.global.flipH);
					return true;
				case enums.KEY.Z:
					if(param.shift){
						record.redo();
					}else{
						record.undo();
					}
					return true;
			}
		}else if(e == event.events.note.load){
			this.checkMenuItems();
			this.checkBackground();
		}else if(e == event.events.note.unload){
			this.checkBackground();
		}else if(e == event.events.global.drop){
			if(!param || !param.dataTransfer.files.length){
				return;
			}
			var file = param.dataTransfer.files[0].path;
			var ext = path.extname(file);
			if(ext == '.jpg' || ext == '.png'){
				var note = require('../note/manager');
				note.updateBG(file);
				this.checkBackground();
				return event.result.stopAll;
			}
		}

		return false;
	},

    doLangReplace: function(){
        var items = this.parent.find('span[data-i18n]');
        for(var i=0;i<items.length;i++){
            var key = items.eq(i).data('i18n');
            items.eq(i).text(config.i18n(key));
        }
        items = this.parent.find('li[data-i18n]');
        for(var i=0;i<items.length;i++){
            var key = items.eq(i).data('i18n');
			var item = items.eq(i);
			if(item.find('i').size()){
				item.find('i').text(config.i18n(key));
			}else{
				items.eq(i).text(config.i18n(key));
			}
        }
    },

	/**
	 * 根据当前的编辑模式, 切换一些菜单的可用性
	 */
	checkMenuItems: function() {
		var note = require('../note/manager');
		var chart = note.getNote('main');
		if(chart){
			var mode = chart.meta.mode;
			//catch辅助线
			if(mode <  3){
				this.parent.find('li[data-action="aux.grid.dialog"]').hide();
				this.parent.find('li[data-action="touch.note"]').show();
			}else if(mode == 3){
				this.parent.find('li[data-action="aux.grid.dialog"]').show();
				this.parent.find('li[data-action="touch.note"]').hide();
			}
			if(mode < 3 && util.getJsonChainValue(chart, 'meta.mode_ext.column') == 8){
				this.parent.find('li[data-action="mc2bms.file"]').show();
			}else{
				this.parent.find('li[data-action="mc2bms.file"]').hide();
			}

		}
	},

	checkBackground: function () {
		var note = require('../note/manager');
		var chart = note.getNote('main');
		if(chart && chart.meta.background){
			$("#blurbg").css('backgroundImage','url("'+note.getFilePath(chart.meta.background)+'")');
			$("body").addClass("hasbg");
		}else{
			$("#blurbg").css('backgroundImage','url()');
			$("body").removeClass("hasbg");
		}
	}

};

module.exports = ret;